package com.tushare.util;

import com.tushare.entity.Daily;

import java.util.ArrayList;
import java.util.List;

public class CalMacdUtil {
    private static final int SHORT_TIME = 12;
    private static final int LONG_TIME = 26;
    private static final int MID = 9;

    /*
     * 计算MACD
     */
    public static List<Float> calcMACD(List<Daily> dailyList) {
        List<Float> macd = new ArrayList<>();
        List<Float> dif = calcDIF(dailyList);
        List<Float> dea = calcDEA(dif);
        for (int i = 0, l = dailyList.size(); i < l; i++) {
            float d = (dif.get(i) - dea.get(i)) * 2;
            macd.add(d);
        }
        return macd;
    }

    /*
     * 计算DIF快线，用于MACD
     */
    private static List<Float> calcDIF(List<Daily> data) {
        List<Float> dif = new ArrayList<>();
        List<Float> emaShort = calcEMA(SHORT_TIME, data);
        List<Float> emaLong = calcEMA(LONG_TIME, data);
        for (int i = 0, l = data.size(); i < l; i++) {
            float d = emaShort.get(i) - emaLong.get(i);
            dif.add(d);
        }
        return dif;
    }

    /*
     * 计算DEA慢线，用于MACD
     */
    private static List<Float> calcDEA(List<Float> dif) {
        List<Float> ema = new ArrayList<>();
        float a = 2.0f / (MID + 1);
        ema.add(dif.get(0));
        for (int i = 1, l = dif.size(); i < l; i++) {
            float d = a * dif.get(i) + (1 - a) * ema.get(i - 1);
            ema.add(d);
        }
        return ema;
    }

    /*
     * 计算EMA指数平滑移动平均线，用于MACD
     */
    private static List<Float> calcEMA(int n, List<Daily> data) {
        List<Float> ema = new ArrayList<>();
        float a = 2.0f / (n + 1);
        ema.add(data.get(0).getClose());
        for (int i = 1, l = data.size(); i < l; i++) {
            float v = a * data.get(i).getClose();
            float v1 = (1 - a) * ema.get(i - 1);
            ema.add(v + v1);
        }
        return ema;
    }

}
